var defaultAreaIcon = "../img/defaultDivision.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.53884704455731;
var centerY = 29.7219072675705;
var currentGraphic;
var drawHandler;
var oldPoint;
var dynamicTowPointFiveD;
var gsvc;// 测量面积

require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct", "esri/tasks/GeometryService" ], function(Map,
		Color, Graphic, InfoTemplate, SpatialReference, HeatmapRenderer,
		OverviewMap, Scalebar, Measurement, Units, TDTLayer, TDTAnnoLayer,
		TDT_ImgLayer, TDT_ImgAnnoLayer, GraphicsLayer,
		ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, FeatureLayer,
		Point, Polyline, Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
		PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
		LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
		domConstruct, GeometryService) {

	map = new Map("map", {
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 17,
		minZoom : 8
	});

	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});

	// 显示比例尺
	scalebar.show();
	drawHandler = Draw;
	var vec = new TDTLayer();// 切片线画图
	var veca = new TDTAnnoLayer();// 切片标注
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);

	gsvc = new GeometryService(arcGisUrl
			+ "/arcgis/rest/services/Utilities/Geometry/GeometryServer");

	dynamicTowPointFiveD = new ArcGISTiledMapServiceLayer(arcGisUrl
			+ "/arcgis/rest/services/ByMap/MapServer");
	dynamicTowPointFiveD.hide();
	dynamicTowPointFiveD.id = "dynamicTowPointFiveD";
	map.addLayer(dynamicTowPointFiveD);

	map.graphics.on("mouse-over", function(evt) {
		console.log("graphicslayer:mouse-over");

		var symbol = getPolygonMouseInSymbol();
		evt.graphic.setSymbol(symbol);
	});

	map.graphics.on("mouse-out", function(evt) {
		console.log("graphicslayer:mouse-out");
		var symbol;
		if (evt.graphic.attributes && evt.graphic.attributes.division) {
			symbol = getPolygonDefaultSymbolHasDivision();
		} else {
			symbol = getPolygonDefaultSymbolHasNoDivision();
		}
		evt.graphic.setSymbol(symbol);
	});

	map.graphics.on("mouse-down", function(evt) {
		console.log("graphicslayer:mouse-down");
		if (evt.graphic) {
			currentGraphic = evt.graphic;
		}
		if (currentGraphic) {
			oldPoint = evt.mapPoint;
			currentGraphic.isMouseDown = true;
			isDrag=false;
			map.disableMapNavigation();
			map.disablePan();
		}
	});
	map.on("mouse-drag", function(evt) {

		console.log("map:mouse-drag");
		if (currentGraphic) {
			if (currentGraphic.isMouseDown) {
				var x_deviation = evt.mapPoint.x - oldPoint.x;
				var y_deviation = evt.mapPoint.y - oldPoint.y;
				oldPoint = evt.mapPoint;

				var geometry = currentGraphic.geometry;
				for (var i = 0; i < geometry.rings[0].length; i++) {
					geometry.rings[0][i][0] = geometry.rings[0][i][0]
							+ x_deviation;
					geometry.rings[0][i][1] = geometry.rings[0][i][1]
							+ y_deviation;
				}
				currentGraphic.setGeometry(geometry);
				isDrag=true;
			}
		}
	});
	map.on("mouse-up", function(evt) {
		console.log("map:mouse-up");
		if (currentGraphic) {
			oldPoint = null;
			map.enableMapNavigation();
			map.enablePan();
			currentGraphic.isMouseDown = false;
			if (currentGraphic.attributes) {
				if (currentGraphic.attributes.id) {
					if(currentGraphic==evt.graphic){
						EditMapPoint(evt);
					}else if(evt.graphic){
						EditMapPointC(currentGraphic);
					}
					
				}
			}
		}
	});
	toolbar = new Draw(map);
	dojo.connect(toolbar, "onDrawEnd", addToMap);
	getUndingArea();
});
function EditMapPoint(evt) {
	if (evt.graphic) {
		var attr = evt.graphic.attributes;
		editModule(attr);
	}
};
function EditMapPointC(graphic) {
		var attr = graphic.attributes;
		editModule(attr);
};
// 地图添加网格
jQuery('.addAreaInMapBtn').on('click', function() {
	var selectNodeId = getTreeIdForSelectNode();
	if (selectNodeId == "" || selectNodeId == "0") {
		message("请选择区域!");
		return;
	}
	toolbar.activate(drawHandler.POLYGON);
	$(".cancelAreaInMapBtn").attr("disabled", false);
	$(".addAreaInMapBtn").attr("disabled", true);
	$('body').css('cursor', 'crosshair');
	map.setMapCursor('crosshair');
});
// 显示2.5D地图
jQuery('.showThreeDInMapBtn').on('click', function() {
	if (dynamicTowPointFiveD) {
		if ($(".showThreeDInMapBtn").html() == "2.5D展示") {
			dynamicTowPointFiveD.show();
			$(".showThreeDInMapBtn").html("2.5D隐藏");
		} else {
			dynamicTowPointFiveD.hide();
			$(".showThreeDInMapBtn").html("2.5D展示");
		}

	}
});
var isJudgePolygonOverlap=false;
//叠加检测
jQuery('.judgePolygonOverlapBtn').on('click', function() {
		if ($(".judgePolygonOverlapBtn").html() == "开启叠加检测") {
			$
			.springLemonDialog({
				content : '开启叠加检测会降低效率,是否确认开启?',// 确认文本
				clickButton : function(sender,
						modal, index) {// 按钮事件处理
					if (index == 0) {
						isJudgePolygonOverlap=true;
						$(".judgePolygonOverlapBtn").html("关闭叠加检测");
					} else {
					}
					$(this).closeDialog(modal);
				}
			});
		} else {
			isJudgePolygonOverlap=false;
			$(".judgePolygonOverlapBtn").html("开启叠加检测");
		}
});
// 地图取消添加网格
jQuery('.cancelAreaInMapBtn').on('click', function() {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelAreaInMapBtn").attr("disabled", true);
	$(".addAreaInMapBtn").attr("disabled", false);
	$('body').css('cursor', 'default');
	map.setMapCursor('default');
});
/*
 * //添加菜单，弹出弹窗 jQuery('.showNoDivisionAreaInMapBtn').on('click', function() {
 * getUndingArea(); });
 */

// 获取当前选择树节点
function getTreeIdForSelectNode() {
	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var id = "";
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode && selectNode.id != "0") {
			id = selectNode.id;
		}
	}
	return id;
}
function addToMap(geometry) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelAreaInMapBtn").attr("disabled", true);
	$(".addAreaInMapBtn").attr("disabled", false);

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块
	// 判断几何图形的类型
	switch (geometry.type) {
	case "point":
		var symbolurl = getIconForSelectNode();
		var symbol = new esri.symbol.PictureMarkerSymbol({
			"url" : symbolurl, // 图标路径
			"width" : 20, // 图标的宽度
			"height" : 20
		// 图标的高度
		});
		break;
	case "polyline":
		var symbol = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([ 255,
						0, 0 ]), 1);
		break;
	case "polygon":
		//碰撞检测
		$(".saveBtn").attr("disabled",false);
		$("#judgePolygonOverlapTitle").html("");
		if(isJudgePolygonOverlap){
			$(".saveBtn").attr("disabled",true);
			JudgePolygonOverlap(geometry,"");
		}
		var symbol = getPolygonDefaultSymbolHasDivision();
		/*
		 * // 测量面积 require( [ "esri/tasks/AreasAndLengthsParameters" ],
		 * function(AreasAndLengthsParameters) { var areasAndLengthParams = new
		 * AreasAndLengthsParameters(); areasAndLengthParams.lengthUnit =
		 * esri.tasks.GeometryService.UNIT_KILOMETER;
		 * areasAndLengthParams.areaUnit =
		 * esri.tasks.GeometryService.UNIT_SQUARE_KILOMETERS; gsvc.simplify([
		 * geometry ], function(simplifiedGeometries) {
		 * areasAndLengthParams.polygons = simplifiedGeometries;
		 * gsvc.areasAndLengths(areasAndLengthParams); }); });
		 */
		break;
	case "extent":
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;
	case "multipoint":
		var symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 0, 0, 0 ]), 1), new dojo.Color([ 255,
						255, 0, 0.5 ]));
		break;
	}
	var graphic = new esri.Graphic(geometry, symbol);
	map.graphics.add(graphic); // 将绘图加入到图层中
	currentGraphic = graphic;

	// 进行投影转换，完成后调用projectComplete
	MeasureGeometry(geometry);

	// 打开部件基础信息窗口
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	jQuery('#id').val('');
	$("#areaId").val(getTreeIdForSelectNode());
};
// 投影转换完成后调用方法
function MeasureGeometry(geometry) {
	require(
			[ "esri/tasks/AreasAndLengthsParameters",
					"esri/tasks/LengthsParameters" ],
			function(AreasAndLengthsParameters, LengthsParameters) {
				// 如果为线类型就进行lengths距离测算
				if (geometry.type == "polyline") {
					var lengthParams = new esri.tasks.LengthsParameters();
					lengthParams.polylines = [ geometry ];
					lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					lengthParams.geodesic = true;
					lengthParams.polylines[0].spatialReference = new esri.SpatialReference(
							4326);
					gsvc.lengths(lengthParams);
					dojo.connect(gsvc, "onLengthsComplete", outputDistance);
				}
				// 如果为面类型需要先进行simplify操作在进行面积测算
				else if (geometry.type == "polygon") {
					var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
					areasAndLengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_METERS;
					this.outSR = new esri.SpatialReference({
						wkid : 102113
					});
					gsvc
							.project(
									[ geometry ],
									this.outSR,
									function(geometry) {
										gsvc
												.simplify(
														geometry,
														function(
																simplifiedGeometries) {
															areasAndLengthParams.polygons = simplifiedGeometries;
															areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(
																	102113);
															gsvc
																	.areasAndLengths(areasAndLengthParams);
														});
									});
					dojo.connect(gsvc, "onAreasAndLengthsComplete",
							outputAreaAndLength);
				}
			});
};
// 显示测量面积
function outputAreaAndLength(result) {
	$("#gridArea").val(result.areas[0].toFixed(3));
	console.log(result.areas[0].toFixed(3) + "平方米");
};
// 显示测量距离
function outputDistance(result) {

	console.log(result.lengths[0].toFixed(3) + "米");
}
// 返回按钮
jQuery('.goBackBtn')
		.on(
				'click',
				function() {
					if (!currentGraphic) {
						return;
					}
					if ($("#id").val() == null || $("#id").val() == "") {
						map.graphics.remove(currentGraphic); // 将绘图从图层中移除
						currentGraphic = null;
					} else {
						var geometry = currentGraphic.geometry;
						var gridDetails = currentGraphic.gridDetails;

						for (var i = 0; i < gridDetails.length; i++) {
							geometry.rings[0][gridDetails[i].longlatOrder][0] = gridDetails[i].longtitude;
							geometry.rings[0][gridDetails[i].longlatOrder][1] = gridDetails[i].latitude;
						}
						currentGraphic.setGeometry(geometry);
					}
				});
$(function() {
	// 1 初始化分页信息
	initPage();
	// 9 初始化树结构
	initZtree();
	initUnbindDivisionGridPage();

	/* showEditDataByTxt("#typeOpt","特征点"); */
	$("#typeOpt").find("option:contains('门(楼)牌')").attr("selected", true);

});

// 8 撤销查询
jQuery('.resetBtn2').on('click', function() {

	jQuery('#search2').val('');
	serverUbData.key = '';
	serverUbTable.draw();
});
// 7 点击查询按钮
$(".searchBtn2").click(function() {

	serverUbData.key = jQuery("#search2").val();
	serverUbTable.draw();
});

var level;
var serverData = {};
var serverTable;
// 初始化 层级树
var primaryNode = [];
// //////////////初始化模型的树结构/////////////////////////
var modalSetting = {
	edit : {
		enable : true,
		showRemoveBtn : false,
		showRenameBtn : false,
		drag : {
			isCopy : false,
			isMove : false,
			prev : false,
			next : false,
			inner : false
		}
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	check : {
		enable : false,
		chkStyle : "radio",
		radioType : "level"
	},
	callback : {
		onClick : bindNodePrepare,
		onNodeCreated : zTreeOnNodeCreated
	}
};
var serverUbData = {};
var serverUbTable;
function initUnbindDivisionGridPage() {
	serverUbTable = jQuery('#unbindDivisionGridTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "post",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/gridBuilding/getUnbindPage',
							"data" : function(d) {
								return $.extend({}, d, serverUbData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : null,
									defaultContent : "",
									render : function(data, type, full, meta) {
										var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
												+ '<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>'
												+ '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>'

										return operate;
									}
								}, {
									data : 'gridIdentify'
								}, {
									data : 'gridName',
								}, {
									data : 'gridScale',
								}, {
									data : 'gridArea'
								}, {
									data : 'gridState.title'
								}/*
									 * , { data : 'typeOpt.title' }, { data :
									 * 'gridToArcGisObjectId' }
									 */, {
									data : "division.divisionName"

								}

						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverUbTable.off('click', 'tr');
							serverUbTable
									.on(
											'click',
											'tr',
											function(event) {
												event = event || window.event;
												var target = event.target
														|| event.scrElement;
												var data = serverUbTable.row(
														this).data();

												if (target.className
														.indexOf('fa-remove') != -1
														|| target.className
																.indexOf('delBtn') != -1) {
													// 2 删除
													deleteGridById(data);
												}

												if (target.className
														.indexOf('fa-pencil') != -1
														|| target.className
																.indexOf('editBtn') != -1) {
													// 3 编辑
													editModule(data);
												}
												if (target.className
														.indexOf('fa-sign-in') != -1
														|| target.className
																.indexOf('addNode') != -1) {
													bindNode(data);
												}
												if (target.className
														.indexOf('fa-unlock') != -1
														|| target.className
																.indexOf('removeNode') != -1) {

													unbindNode(data);
												}
												return;
											});
						}
					});

};
// 13 状态选择
$("#gridStateSelect").change(function() {
	var gridStateId = $(this).val();
	var gridStateName = $('#gridStateSelect option:selected').text();
	if (gridStateId == '00000') {
		gridStateName = '';
	}

	serverData.key = jQuery("#search").val();
	serverData.tree = gridStateId;
	serverTable.draw();
});
// 12区域选择
$("#divisionSelect").change(function() {
	var divisionId = $(this).val();
	var divisionName = $('#divisionSelect option:selected').text();
	if (divisionId == '00000') {
		divisionName = '';
	}
	serverData.key = jQuery("#search").val();
	serverData.tree = gridStateId;
	serverTable.draw();
});
// 11 绑定
function bindNode(data) {
	var gridId = data.id;
	var divisionId = $("#divisionId").val();
	if (divisionId == '0' || '' == divisionId) {
		message("选择根节点之外的节点进行绑定!");
		return;
	}
	$("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridBuilding/bindNode/" + gridId + "/" + divisionId,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				// createArea(result.data.data,true);
				updateArea(result.data.data, true);
			}
			message(result.msg);
			$("#right").mLoading("hide");
		}
	});
};
// 10网格绑定区域准备
function bindNodePrepare(e, treeId, treeNode) {
	var divisionId = treeNode.id;

	currentGraphic = null;
	if (divisionId == undefined || '0' == divisionId) {
		$("#divisionId").val("");
		return;
	}

	$("#divisionId").val(divisionId);

	// 同时作为过滤条件刷新已绑定信息
	serverData.key = jQuery("#search").val();

	/*
	 * var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree"); var selectNodes =
	 * treeObj.getSelectedNodes(treeObj); if (selectNodes) { var selectNode =
	 * selectNodes[0]; if (selectNode) { serverData.tree = selectNode.id; } }
	 */
	serverData.tree = divisionId;
	serverTable.draw();
	$.ajax({
		url : rootPath + "/ui/gridBuilding/getBindingByArea?areaId=" + divisionId,
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.code <= 0) {
				message("获取网格失败!");
			} else {
				if (result.data) {
					/* map.graphics.clear(); */

					var graphics = map.graphics.graphics;
					for (var i = 0; i < graphics.length; i++) {
						if (graphics[i]) {
							if (graphics[i].attributes) {
								if (graphics[i].attributes.division) {
									map.graphics.remove(graphics[i]);
									i--;
								}
							}
						}
					}
					for (var i = 0; i < result.data.length; i++) {
						var temp = createArea(result.data[i], true);
						if (i == 0) {
							map.centerAndZoom(temp.geometry.getCentroid(), map
									.getLevel());
						}
					}
				}
			}
		}
	});
};
// 获取未绑定列表
function getUndingArea() {
	$.ajax({
		url : rootPath + "/ui/gridBuilding/getWithOutArea",
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.code <= 0) {
				message("获取地图未绑定区域网格失败!");
			} else {
				if (result.data) {
					for (var i = 0; i < result.data.length; i++) {
						createArea(result.data[i], false)
					}
				}
			}
		}
	});
};
// 更新
function updateArea(data, isDivision) {
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data.id) {
					if (isDivision) {
						symbol = getPolygonDefaultSymbolHasDivision();
					} else {
						symbol = getPolygonDefaultSymbolHasNoDivision();
					}
					graphics[i].setSymbol(symbol);
					graphics[i].attributes = data;
					graphics[i].gridDetails = data.details;
					return;
				}
			}
		}
	}
};

// 创建图形
function createArea(data, isDivision) {
	if (data.details) {
		var rings = [];

		var points = [];

		for (var i = 0; i < data.details.length; i++) {
			points.push([]);
		}

		for (var i = 0; i < data.details.length; i++) {
			var point = [];
			point.push(data.details[i].longtitude);
			point.push(data.details[i].latitude);

			points[data.details[i].longlatOrder] = point;
		}
		rings.push(points);

		var symbol;
		if (isDivision) {
			symbol = getPolygonDefaultSymbolHasDivision();
		} else {
			symbol = getPolygonDefaultSymbolHasNoDivision();
		}

		var myPolygon = {
			"geometry" : {
				"rings" : rings,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" : {
				"color" : [ 0, 0, 0, 64 ],
				"outline" : {
					"outline" : [ 0, 0, 0, 255 ],
					"width" : 1,
					"type" : "esriSLS",
					"style" : "esriSFSSolid"
				}
			}
		};

		var graphic = new esri.Graphic(myPolygon);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.gridDetails = data.details;
		map.graphics.add(graphic);

		return graphic;
		/*
		 * var textSymbol = new esri.symbol.TextSymbol(data.gridIdentify); var
		 * point=graphic.geometry.getCentroid(); text_graphic = new
		 * esri.Graphic(point,textSymbol); map.graphics.add(text_graphic);
		 */
	}

};
function getPolygonMouseInSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 255, 0,
					0.75 ]));
	return symbol;
}
function getPolygonDefaultSymbolHasDivision() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 145, 0,
					0.35 ]));

	return symbol;
}
function getPolygonDefaultSymbolHasNoDivision() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color(
							[ 255, 0, 0 ]), 2), new dojo.Color([ 255, 255, 0,
					0.35 ]));
	return symbol;
}
// 设置tree图标大小
function zTreeOnNodeCreated(event, treeId, treeNode) {
	if (treeNode.type != "folder") {
		$('#' + treeNode.tId + '_ico').css(
				"background",
				"url('" + treeNode.icon
						+ "') center center/16px 16px no-repeat");
	}
}
// 9 初始化树结构
function initZtree() {

	$.ajax({
		url : rootPath + "/ui/gridBuilding/getAllNodes",
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				id : 0,
				name : "区域层级",
				open : "true",
				icon : defaultAreaIcon
			// iconSkin:"diy03"
			});
			for (var i = 0; i < data.nodes.length; i++) {
				if (data.nodes[i].icon != undefined
						&& data.nodes[i].icon != "") {
				} else {
					data.nodes[i].icon = defaultAreaIcon; 
				}
				primaryNode.push(data.nodes[i]);
			}
			$.fn.zTree.init($("#gridAreaTree"), modalSetting, primaryNode);
		}
	});
};
function unbindNode(data) {
	if (data.division == null || undefined == data.division) {
		message("尚未绑定区域");
		return false;
	}
	var id = data.id;
	$("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridBuilding/unbindNode/" + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				// deleteAreaMap(data);
				updateArea(result.data.data, false);
			}
			message(result.msg);
			$("#right").mLoading("hide");
		}
	});
};
var graphicArrays = [];
// 地图上面快捷查询
jQuery('.searchMapBtn').on(
		'click',
		function() {
			/*
			 * query_all(map.graphics,$("#searchMap").val(),function (evt) {
			 * map.centerAt(); });
			 */
			graphicArrays = getcurrentGraphicsByValue($("#searchMap").val());

			var symbol = getPolygonMouseInSymbol();

			for (var i = 0; i < graphicArrays.length; i++) {
				if (i == 0) {
					map.centerAndZoom(graphicArrays[i].geometry.getCentroid(),
							map.getLevel());
				}
				graphicArrays[i].setSymbol(symbol);
			}
		});
jQuery('.resetMapBtn').on('click', function() {
	jQuery('#searchMap').val('');

	if (graphicArrays) {
		var symbol;

		for (var i = 0; i < graphicArrays.length; i++) {
			if (graphicArrays[i].attributes.division) {
				symbol = getPolygonDefaultSymbolHasDivision();
			} else {
				symbol = getPolygonDefaultSymbolHasNoDivision();
			}
			graphicArrays[i].setSymbol(symbol);
		}
		graphicArrays = null;
	}
});

function getcurrentGraphicsByValue(txt) {
	var graphicArray = [];
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i] && graphics[i].geometry.type == "polygon") {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.gridIdentify
						&& graphics[i].attributes.gridIdentify.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridName
						&& graphics[i].attributes.gridName.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridState
						&& graphics[i].attributes.gridState.title.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridMemo
						&& graphics[i].attributes.gridMemo.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				}
			}
		}
	}
	return graphicArray;
};

// 8 撤销查询
jQuery('.resetBtn').on('click', function() {
	jQuery('#search').val('');
	serverData.key = '';

	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			serverData.tree = selectNode.id;
		}
	}
	serverTable.draw();
});
// 7 点击查询按钮
$(".searchBtn").click(function() {
	serverData.key = jQuery("#search").val();
	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			serverData.tree = selectNode.id;
		}
	}
	serverTable.draw();
});
var isDrag=false;
// 6 点击编辑按钮打开模态框
function editModule(data) {
	$(".saveBtn").attr("disabled",false);
	$("#judgePolygonOverlapTitle").html("");
	
	if(isDrag&&isJudgePolygonOverlap&&currentGraphic){
		$(".saveBtn").attr("disabled",true);
		JudgePolygonOverlap(currentGraphic.geometry,currentGraphic.attributes.id);
	}
	getcurrentGraphic(data.id);
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	// 初始化数据
	// initStateAndTpye();

	// 数据回显
	$("#id").val(data.id);
	$("#gridName").val(data.gridName);
	$("#gridArea").val(data.gridArea);
	$("#gridIdentify").val(data.gridIdentify);
	$("#gridMemo").val(data.gridMemo);
	/* $("#areaId").val(data.areaId); */
	$("#createTime").val(moment(data.createTime).format('YYYY/MM/DD'));
	$("#gridToArcGisObjectId").val(data.gridToArcGisObjectId);
	$("#gridScale").val(data.gridScale);
	showEditData("#gridState", data.gridState.id);
	if (data.typeOpt) {
		showEditData("#typeOpt", data.typeOpt.id);
	}
	if (data.division) {
		$("#areaId").val(data.division.id);
		showEditData("#areaId", data.division.id);
	} else {
		$("#areaId").val("");
		showEditData("#areaId", "");
	}

	$("#typeOpt").prop("disabled", "disabled").css("background-color",
			"#BEBEBE");

	$("#gridIdentify").prop("readonly", "readonly");
};

function showEditData(str, data) {
	$(str).each(function() {
		$(this).children("option").each(function() {
			if ($(this).val() == data) {
				$(this).prop("selected", true);
			}
		});
	});
};
function showEditDataByTxt(str, data) {
	$(str).each(function() {
		$(this).children("option").each(function() {
			if ($(this).text() == data) {
				$(this).prop("selected", true);
			}
		});
	});
};
function getcurrentGraphic(data) {
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data) {
					currentGraphic = graphics[i];
					return;
				}
			}
		}
	}
	currentGraphic = null;
};

// 专供地图查询使用
function query_all(layer, text, callback) {
	require([ "esri/tasks/query", "esri/tasks/QueryTask" ], function(Query,
			QueryTask) {
		if (text == "") {
			Lobibox.window({
				title : "提示信息",
				content : "请输入您所查询的信息",
				width : 500,
				height : 100
			});
		}
		text = "gridIdentify like '%" + text + "%'";
		var tasks = new QueryTask(arcGisUrl
				+ "/arcgis/rest/services/CZbujian1/MapServer/13");
		var q = new Query();
		q.returnGeometry = true;
		q.outSpatialReference = map.spatialReference;
		q.outFields = [ "*" ];
		q.where = text;
		tasks.execute(q, query_out);
	});
};
function query_out(evt) {
	switch (evt.geometryType) {
	case "esriGeometryPolygon":
		if (!evt.features.length) {
			Lobibox.window({
				title : "提示信息",
				content : "未查询到您所查询的信息",
				width : 500,
				height : 100
			});
		} else if (evt.features.length == 1 || evt.features.length == 2) {
			var map_point = evt.features[0].geometry.getCentroid();
			map.centerAndZoom(evt.features[0].geometry.getCentroid(), map
					.getLevel());
			var layerPoint = map.toScreen(map_point);
		} else {

		}
	}

}

// 5 点击保存按钮添加单元网格信息
$(".saveBtn")
		.click(
				function() {

					if (jQuery("#gridAreaEditForm")
							&& !jQuery("#gridAreaEditForm").Validform({
								tiptype : 3,
								showAllError : true
							}).check(false)) {
						return;
					}
					var gridAreaDetail = [];
					if (currentGraphic) {
						var geometry = currentGraphic.geometry;
						for (var i = 0; i < geometry.rings[0].length; i++) {
							var point = {
								"longtitude" : geometry.rings[0][i][0],
								"latitude" : geometry.rings[0][i][1],
								"longlatOrder" : i
							};
							gridAreaDetail.push(point);
						}
					}
					var stateId = $("#gridState").val();
					var typeId = $("#typeOpt").val();
					var typeName = $("#typeOpt option:selected").text();

					var id = $("#id").val();

					var gridArea = $("#gridArea").val();

					var gridMemo = $("#gridMemo").val();
					var areaId = $("#areaId").val();
					var gridToArcGisObjectId = $("#gridToArcGisObjectId").val();
					var createTime = $("#createTime").val();
					var gridName = $("#gridName").val();
					var gridScale = $("#gridScale").val();
					var data = {};
					// var gridAreaInfo = {};

					var length = gridAreaDetail.length;

					/*
					 * if (typeName == "网格") { if (length < 3) {
					 * message("不是网格类型,请重新选择类型"); return false; } } if (typeName ==
					 * "特征点") { if (length != 1) { message("不是特征点类型,请重新选择类型");
					 * return false; } }
					 */

					if (id == '') {// 添加
						gridAreaInfo = {
							"gridArea" : gridArea,
							"gridName" : gridName,
							"gridScale" : gridScale,
							// "gridIdentify" : gridIdentify,
							"gridMemo" : gridMemo,
							"gridToArcGisObjectId" : gridToArcGisObjectId,
							"gridState" : {
								"id" : stateId
							},
							"typeOpt" : {
								"id" : typeId
							}
						/*
						 * , "division" : { "id" : areaId }
						 */
						};
						if (areaId != undefined && areaId != "") {
							gridAreaInfo.division = {
								"id" : areaId
							};
						}
						data = {
							"gridAreaInfo" : gridAreaInfo,
							"gridAreaDetail" : gridAreaDetail
						};
					} else {// 修改
						var gridIdentify = $("#gridIdentify").val();
						// 解绑之后
						/*
						 * if (areaId == null || '' == areaId) { message("请绑定区域");
						 * return; }
						 */

						gridAreaInfo = {
							"id" : id,
							"gridArea" : gridArea,
							"gridScale" : gridScale,
							"gridIdentify" : gridIdentify,
							"gridName" : gridName,
							"gridMemo" : gridMemo,
							"gridToArcGisObjectId" : gridToArcGisObjectId,
							// "updateTime":updateTime,
							"createTime" : createTime,
							"gridState" : {
								"id" : stateId
							},
							"typeOpt" : {
								"id" : typeId
							}
						/*
						 * , "division" : { "id" : areaId }
						 */
						};
						if (areaId != undefined && areaId != "") {
							gridAreaInfo.division = {
								"id" : areaId
							};
						}
						data = {
							"gridAreaInfo" : gridAreaInfo,
							"gridAreaDetail" : gridAreaDetail
						};
					}
					$("#right").mLoading("show");
					$
							.ajax({
								url : rootPath + "/ui/gridBuilding/operateGrid",
								dataType : 'json',
								data : JSON.stringify(data),
								type : 'post',
								contentType : "application/json",
								success : function(result) {
									if (result.code == 1) {
										if (currentGraphic) {
											if ($("#areaid").val() == $(
													"#divisionId").val()
													|| result.data.division == undefined) {
												currentGraphic.attributes = result.data.attributes;
												currentGraphic.gridDetails = result.data.gridDetails;
											} else {
												map.graphics
														.remove(currentGraphic);
											}

										}
										jQuery('#gridAreaModal').modal('hide');
										serverTable.draw(false);
										serverUbTable.draw(false);
									}
									message(result.msg);
									$("#right").mLoading("hide");
								}
							});
				});
function JudgePolygonOverlap(geometry,gridId){
	var points=[];
		for (var i = 0; i < geometry.rings[0].length; i++) {
			var point = {
				"x" : geometry.rings[0][i][0],
				"y" : geometry.rings[0][i][1]
			};
			points.push(point);
		}
		var data = {
				"points" : points,
				"gridId":gridId
			};
		$
		.ajax({
			url : rootPath + "/ui/gridBuilding/JudgePolygonOverlap",
			dataType : 'json',
			data : JSON.stringify(data),
			type : 'post',
			contentType : "application/json",
			success : function(result) {
				if (result.code == 1) {
					$(".saveBtn").attr("disabled",result.data.overlap);
					if(result.data.overlap==true){
						$("#judgePolygonOverlapTitle").html("判断重叠失败!");
						if(result.data.grid){
							$("#judgePolygonOverlapTitle").html("与 "+result.data.grid.gridName+":编号:"+result.data.grid.gridIdentify+"网格发生重叠!");
						}else{
							$("#judgePolygonOverlapTitle").html("与 未知网格发生重叠!");
						}
					}
				}else{
					$(".saveBtn").attr("disabled",true);
					$("#judgePolygonOverlapTitle").html("判断重叠失败!");
				}
			}
		});		
}
// 4 准备预先的数据[状态,类型]
function initStateAndTpye() {
	$("#typeOpt option").remove();
	$("#gridState option").remove();
	$.ajax({
		url : rootPath + "/ui/gridBuilding/initStateAndTpye",
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var types = result.data.type;
				var states = result.data.state;
				$.each(types, function() {
					$("#typeOpt").append(
							"<option value='" + this.id + "'>" + this.title
									+ "</option>");
				});
				$.each(states, function() {
					$("#gridState").append(
							"<option value='" + this.id + "'>" + this.title
									+ "</option>");
				});
			}
		}
	});
};
// 3 点击添加按钮弹出模态框
$(".addBtn").click(function() {
	jQuery('#id').val('');
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	$("#areaId").val(getTreeIdForSelectNode());

	/*
	 * var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree"); var selectNodes =
	 * treeObj.getSelectedNodes(treeObj); if (selectNodes) { var selectNode =
	 * selectNodes[0]; if (selectNode) { $("#areaId").val(selectNode.id); } }
	 */
	// 4 准备预先的数据[状态,类型]
	// initStateAndTpye();
});
// 2 删除网格信息
function deleteGridById(data) {
	var gridId = data.id;

	$.ajax({
		url : rootPath + "/ui/gridBuilding/operateGrid/" + gridId,
		dataType : 'json',
		type : 'POST',
		data : '_method=DELETE',
		success : function(result) {
			message(result.msg);
			if (result.code == 0) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				deleteAreaMap(data);
			}
		}
	});
}
function deleteAreaMap(data) {
	/*
	 * var graphics = map.graphics.graphics; for (var i=0;i<graphics.length;i++) {
	 * if (graphics[i]) { if(graphics[i].attributes){
	 * if(graphics[i].attributes.id==data.id){
	 * console.log("remove:"+graphics[i].attributes.id);
	 * map.graphics.remove(graphics[i]); break; } } } }
	 */
	getcurrentGraphic(data.id);
	if (currentGraphic) {
		map.graphics.remove(currentGraphic);
	}
}
// 1 初始化分页信息
function initPage() {

	serverTable = jQuery('#bindDivisionGridTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "post",
							"cache" : false,
							"url" : window.rootPath + '/ui/gridBuilding/getpage',
							"data" : function(d) {
								return $.extend({}, d, serverData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : null,
									defaultContent : "",
									render : function(data, type, full, meta) {
										var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
												+ '<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>'

												+ '<button type="button" class="btn btn-sm btn-danger removeNode" title="解绑"><i class="fa fa-unlock"></i></button>';
										return operate;
									}
								}, {
									data : 'gridIdentify'
								}, {
									data : 'gridName',
								}, {
									data : 'gridScale',
								}, {
									data : 'gridArea'
								}, {
									data : 'gridState.title'
								}/*
									 * , { data : 'typeOpt.title' }, { data :
									 * 'gridToArcGisObjectId' }
									 */, {
									data : "division.divisionName"

								}

						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverTable.off('click', 'tr');
							serverTable
									.on(
											'click',
											'tr',
											function(event) {
												event = event || window.event;
												var target = event.target
														|| event.scrElement;
												var data = serverTable
														.row(this).data();

												if (target.className
														.indexOf('fa-remove') != -1
														|| target.className
																.indexOf('delBtn') != -1) {
													// 2 删除
													deleteGridById(data);
												}

												if (target.className
														.indexOf('fa-pencil') != -1
														|| target.className
																.indexOf('editBtn') != -1) {
													// 3 编辑
													editModule(data);
												}
												if (target.className
														.indexOf('fa-sign-in') != -1
														|| target.className
																.indexOf('addNode') != -1) {
													bindNode(data);
												}
												if (target.className
														.indexOf('fa-unlock') != -1
														|| target.className
																.indexOf('removeNode') != -1) {

													unbindNode(data);
												}
												return;
											});
						}
					});

};